package org.xshop.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.xshop.bean.Member;
import org.xshop.mapper.TGoodsCommentMapper;
import org.xshop.model.TGoodsComment;
import org.xshop.model.TOrder;
import org.xshop.model.TStore;
import org.xshop.service.ITGoodsCommentService;
import org.xshop.service.ITMemberService;
import org.xshop.service.ITOrderService;
import org.xshop.service.ITStoreService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.InstanceUtil;

/**
 * <p>
 * 商品评论 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-04-08
 */
@MotanService(interfaceClass = ITGoodsCommentService.class)
@CacheConfig(cacheNames = "TGoodsComment")
public class GoodsCommentService extends BaseServiceImpl<TGoodsComment, TGoodsCommentMapper>
implements ITGoodsCommentService {
    @Autowired
    private ITMemberService memberService;
    @Autowired
    private ITOrderService orderService;
    @Autowired
    private ITStoreService storeService;

    @Override
    public Object queryAll(Map<String, Object> param) {
        int pageNum = param.get("pageNum") == null ? 1 : Integer.parseInt(param.get("pageNum").toString());
        int pageSize = 10;
        param.put("offset", (pageNum - 1) * pageSize);
        param.put("limit", pageSize);
        param.put("enable", "1");
        Pagination<TGoodsComment> page = query(param);
        if (page != null) {
            List<TGoodsComment> resultList = InstanceUtil.newArrayList();
            for (TGoodsComment goodsComment : page.getRecords()) {
                // 用户信息
                Member member = memberService.getBaseInfo(goodsComment.getCreateBy());
                if (member != null) {
                    goodsComment.setAvatar(member.getAvatar());
                    goodsComment.setNickName(member.getNickName());
                    resultList.add(goodsComment);
                }
            }
            page.setRecords(resultList);
        }
        return page;
    }

    @Override
    @Transactional
    public void addComment(Map<String, Object> params) {
        JSONObject order = JSON.parseObject(params.get("order").toString());
        BigDecimal evaluate = order.getBigDecimal("evaluate");
        Long orderId = order.getLong("id");
        Assert.notNull(orderId, "订单异常");
        // 更新订单状态
        TOrder myOrder = orderService.queryById(orderId);
        if (myOrder != null && myOrder.getState().equals("5") && myOrder.getMemberId().equals(params.get("memberId"))) {// 待评价
            JSONArray arr = order.getJSONArray("goods");
            if (arr != null && arr.size() > 0) {
                int commentSize = 0;
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject good = arr.getJSONObject(i);
                    if (good != null && DataUtil.isNotEmpty(good.getString("content"))) {
                        TGoodsComment param = new TGoodsComment();
                        param.setOrderId(orderId);
                        param.setGoodsId(good.getLong("id"));
                        TGoodsComment temp = selectOne(param);
                        if (temp != null) {
                            param = temp;
                        }
                        String url = good.getString("url");
                        if (DataUtil.isNotEmpty(url)) {
                            List<String> imgUrl = JSON.parseArray(url, String.class);
                            param.setImageUrl(String.join(",", imgUrl));
                        }
                        param.setComment(good.getString("content"));
                        param.setCreateBy((Long)params.get("memberId"));
                        param.setScore(evaluate);
                        super.update(param);
                        commentSize++;
                    }
                }
                if (commentSize != 0) {
                    myOrder.setState("6");// 已评价||完成
                    orderService.update(myOrder);
                    TStore store = storeService.queryById(myOrder.getStoreId());
                    BigDecimal count = new BigDecimal(store.getScoreCount().toString());
                    store.setEvaluateScore(
                        store.getEvaluateScore().multiply(count).add(evaluate).divide(count.add(new BigDecimal("1"))));
                    store.setScoreCount(store.getScoreCount() + 1);
                    storeService.update(store);
                }
            }
        }
    }
}
